package datasource

import (
	"delivery-server/config"
	"delivery-server/model"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

func NewMysqlEngine() *xorm.Engine {

	// 初始化数据库引擎
	databaseConfig := config.InitDatabaseConfig()
	configStr := databaseConfig.User + ":" + databaseConfig.Password + "@/" + databaseConfig.Name + "?charset=utf8"
	engine, err := xorm.NewEngine("mysql", configStr)
	if err != nil {
		panic(err.Error())
	}

	// 同步数据库结构：将数据结构实体同步更新到数据库表
	err = engine.Sync2(
		new(model.Category),
		new(model.Dish),
		new(model.DishEvaluation),
		new(model.Message),
		new(model.Order),
		new(model.Place),
		new(model.Restaurant),
		new(model.RestaurantEvaluation),
		new(model.Staffer),
		new(model.StafferEvaluation),
		new(model.User),
		new(model.Voucher),
	)
	if err != nil {
		panic(err.Error())
	}

	// 设置是否显示SQL语句
	engine.ShowSQL(true)

	// 设置最大连接数
	engine.SetMaxOpenConns(10)

	return engine
}
